import { like, count, desc, and } from 'drizzle-orm'
import { rolesListQuerySchema, rolesTable } from '~~/server/db/schema/role'
import { db } from '~~/server/db'

export default defineEventHandler(async (event) => {
  // 验证查询参数
  const query = await readValidatedBody(event, rolesListQuerySchema.parse)

  try {
    const { page, limit, name, sortBy } = query
    const offset = (page - 1) * limit

    // 构建查询条件
    const conditions = []
    if (name) {
      conditions.push(like(rolesTable.name, `%${name}%`))
    }

    const whereCondition = conditions.length > 0 ? and(...conditions) : undefined

    // 排序
    // const orderBy = sortOrder === 'desc' ? desc(rolesTable[sortBy]) : asc(rolesTable[sortBy])
    const orderBy = desc(rolesTable[sortBy])

    // 查询数据
    const users = await db
      .select({
        id: rolesTable.id,
        name: rolesTable.name,
        value: rolesTable.value,
        remark: rolesTable.remark,
        createdAt: rolesTable.createdAt,
        updatedAt: rolesTable.updatedAt
      })
      .from(rolesTable)
      .where(whereCondition)
      .orderBy(orderBy)
      .limit(limit)
      .offset(offset)

    // 查询总数
    const [{ total }] = await db
      .select({
        total: count()
      })
      .from(rolesTable)
      .where(whereCondition)
    setResponseStatus(event, 200)
    return {
      data: users,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    }
  } catch (error: any) {
    console.error('Get roles list error:', error)
    throw createError({
      statusCode: 500,
      message: '获取权限列表失败'
    })
  }
})
